<?php
/**
 * User Address Model
 *
 * @Author: PanChaoZhi <phpzhi@qq.com>
 * @Created: 2019/11/13 12:38
 * @Updated: 2019/11/13 @Name:
 */

namespace app\common\model\user;


use think\Exception;
use think\Model;

class Address extends Model
{
    // 表名
    protected $name = 'user_address';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    /**
     * @param $userId
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserAddress($userId)
    {
        return self::where(['is_del' => 0, 'user_id' => $userId])->select();
    }

    public static function getUserDefaultAddress($userId)
    {
        return self::where(['is_del' => 0, 'user_id' => $userId, 'is_default' => 1])->find();
    }

    public static function detail($user_id, $id)
    {
        return self::get(compact('user_id', 'id'));
    }

    public function edit($userId, $data)
    {
        $data['province'] = $data['address']['province'];
        $data['city'] = $data['address']['city'];
        $data['district'] = $data['address']['district'];
        unset($data['address']);
        $data['post_code'] = $data['post_code'] ?? '';

        if ($data['id']) {
            $this->update($data, ['user_id' => $userId, 'id' => $data['id']]);
        } else {
            $data['user_id'] = $userId;
            $this->allowField(true)->save($data);
            if ($data['is_default']) $this->setDefault($userId, $this->getLastInsID());
        }
        return true;
    }

    /**
     * 删除地址
     * @param $userId
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function del($userId, $id)
    {
        if (!$this->where(['is_del' => 0, 'id' => $id, 'user_id' => $userId])->count()) {
            return false;
        }
        $this->where(['user_id' => $userId, 'id' => $id])->update(['is_del' => 1]);
        return true;
    }

    /**
     * 设置默认收货地址（唯一）
     * @param $userId
     * @param $id
     * @return bool
     */
    public function setDefault($userId, $id)
    {
        $clearZeo = $this->where(['user_id' => $userId])->update(['is_default' => 0]);
        $setDefault = $this->where(['id' => $id])->where(['user_id' => $userId])->update(['is_default' => 1]);
        return $clearZeo !== false && $setDefault !== false;
    }
}